function theta=transFromOptim(xFromOptim,index,lowerBound,upperBound,flagCheck) 
% =========================================================================
% transFromOptim
% 
% function xToOptim=transToOptim(theta,index,lowerBound,upperBound,flagCheck) 
% 
% Transforms the original vector THETA for optimization 
% 
%% Inputs 
% *xFromOptim*  Vector of coefficients transformed for optimization 
% *index*  if =0 not transformed 
%          if =1 bounded (a,b)          Must define Lower and Upper Bound
%          if =2 bounded (0,inf) 
%          if =3 bounded (0,1) 
% 
% *lowerBound* a: Only needed if index=1 
% *upperBound* b  Only needed if index=1 
% *flagCheck*  if equal to 1 check for NAN,Inf,Imaginary 
%% Output
% theta: coefficient to be used in the model
% =========================================================================
Ntheta=length(xFromOptim(:)); 
if Ntheta~= length(index(:) ) 
    error('Size mistmatch THETA and INDEX')
end 
if Ntheta~= length(lowerBound(:) ) 
    error('Size mistmatch THETA and lowerBound')
end 
if Ntheta~= length(upperBound(:) ) 
    error('Size mistmatch THETA and upperBound')
end 
theta=zeros(Ntheta,1);
for ii=1:Ntheta
    switch index(ii)
        case 0
            theta(ii)=xFromOptim(ii);
        case 1
            theta(ii)=0.5*( lowerBound(ii)+upperBound(ii) )+...
                0.5*( upperBound(ii)-lowerBound(ii) )*xFromOptim(ii)/...
                sqrt( 1 + (xFromOptim(ii)^2) );
            
        case 2
            theta(ii)=exp( xFromOptim(ii));
        case 3
            theta(ii)=exp( xFromOptim(ii) )/( 1 + exp( xFromOptim(ii) ) );
    end
end
%% Check if any are Imaginary, INF or NAN 
if nargin < 4 || isempty(flagCheck) || flagCheck~=1 
    return 
end 
posNan=isnan(theta); 
if isempty(find(posNan,1))==false; 
    disp('Nan positions in'); 
    printcell( num2cprec(posNan) ); 
end 
posInf=isinf(abs(theta)); 
if isempty(find(posInf,1))==false; 
    disp('Inf positions in'); 
    printcell( num2cprec(posInf ) ); 
end 
posImag=~isreal(theta); 
if isempty(find(posImag,1))==false; 
    disp('Imaginary positions in'); 
    printcell( num2cprec(posImag) ); 
end 

end
    
